<?
class Upload
{
	static function storage_connect($server_no = 0)
    {
        if (!(isset(CGlobal::$ftp_img_conid[$server_no]) && CGlobal::$ftp_img_conid[$server_no])) {
            if (isset(CGlobal::$storage_server[$server_no]['host'], CGlobal::$storage_server[$server_no]['user'], CGlobal::$storage_server[$server_no]['pass'])) {
                CGlobal::$ftp_img_conid[$server_no] = ftp_connect(CGlobal::$storage_server[$server_no]['host']);

                if (CGlobal::$ftp_img_conid[$server_no]) {
                    // Login to FTP Server
                    $login_result = ftp_login(CGlobal::$ftp_img_conid[$server_no], CGlobal::$storage_server[$server_no]['user'], CGlobal::$storage_server[$server_no]['pass']);
                    if ($login_result) {
                        // turn passive mode on
                        ftp_pasv(CGlobal::$ftp_img_conid[$server_no], true);
                        return true;
                    }
                    return false;
                }
            }
            return false;
        }
        return true;
    }

    static function storage_close()
    {
        foreach (CGlobal::$storage_server as $server_no => $server)
        {
            if (isset(CGlobal::$ftp_img_conid[$server_no]) && CGlobal::$ftp_img_conid[$server_no])
            {
                ftp_close(CGlobal::$ftp_img_conid[$server_no]);
                
                CGlobal::$ftp_img_conid[$server_no] = false;
            }
        }
    }

    static function storage_put_file($destFileName, $sourceFileName, $server_no = 0, $mode = FTP_BINARY, $can_duplicate = 0)
    {
        if (CGlobal::$storage_server[$server_no]['server_type'] == 'curl') // Upload via cUrl
        {
            $post_fields['overwrite'] = $can_duplicate;
            $post_fields['filename'] = $destFileName;
            $post_fields['filedata'] = '@'.$sourceFileName;
            $post_fields['secret_key'] = CGlobal::$storage_server[$server_no]['secret_key'];
            $curl_handle = curl_init("http://" . CGlobal::$storage_server[$server_no]['host'].'/upload');

            curl_setopt($curl_handle, CURLOPT_HEADER, 0);
            curl_setopt($curl_handle, CURLOPT_VERBOSE, 0);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
            curl_setopt($curl_handle, CURLOPT_POST, true);
            curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post_fields);

            //execute the API Call
            $returned_data = curl_exec($curl_handle);
            /*if (curl_errno($curl_handle)) {
                // this would be your first hint that something went wrong
                //die('Couldn\'t send request: ' . curl_error($curl_handle));
                return 'Couldn\'t send request: ' . curl_error($curl_handle);
            } else {
                // check the HTTP status code of the request
                $resultStatus = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
                if ($resultStatus == 200) {
                    // everything went better than expected
                } else {
                    // the request did not complete as expected. common errors are 4xx
                    // (not found, bad request, etc.) and 5xx (usually concerning
                    // errors/exceptions in the remote script execution)
                    //die('Request failed: HTTP status code: ' . $resultStatus);
                    return 'Request failed: HTTP status code: ' . $resultStatus;
                }
            }
            if ($returned_data == 'OK') {
                // everything went better than expected
            } else {
                //die('Request failed: Error: ' . $returned_data);
                return 'Request failed: Error: ' . $returned_data;
            }*/

            curl_close($curl_handle);
            //return $returned_data;
            return (($returned_data == 'OK') ? true : false );
        }
        elseif (self::storage_connect($server_no)) // Upload via FTP
        {
            if (@ftp_put(CGlobal::$ftp_img_conid[$server_no], $destFileName, $sourceFileName, $mode))
            {
                @ftp_chmod(CGlobal::$ftp_img_conid[$server_no], 0777, $destFileName);
                return true;
            }
            
            return false;
        }
    }

    static function storage_put_file_from_url($destFileName, $sourceFileName, $server_no = 0, $mode = FTP_BINARY, $can_duplicate = 1){
        if (CGlobal::$storage_server[$server_no]['server_type'] == 'curl') // Upload via cUrl
        {
            $post_fields['overwrite'] = $can_duplicate;
            $post_fields['filename'] = $destFileName;
            $post_fields['source'] = $sourceFileName;
            $post_fields['secret_key'] = CGlobal::$storage_server[$server_no]['secret_key'];
            $curl_handle = curl_init("http://" . CGlobal::$storage_server[$server_no]['host'].'/upload');
            curl_setopt($curl_handle, CURLOPT_HEADER, 0);
            curl_setopt($curl_handle, CURLOPT_VERBOSE, 0);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
            curl_setopt($curl_handle, CURLOPT_POST, true);
            curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $post_fields);
            //execute the API Call
            $returned_data = curl_exec($curl_handle);
            curl_close($curl_handle);
            //return $returned_data;
            return (($returned_data == 'OK') ? true : false );
        }
        elseif (self::storage_connect($server_no)) // Upload via FTP
        {
            if (@ftp_put(CGlobal::$ftp_img_conid[$server_no], $destFileName, $sourceFileName, $mode))
            {
                @ftp_chmod(CGlobal::$ftp_img_conid[$server_no], 0777, $destFileName);
                return true;
            }

            return false;
        }
    }
   	static function storage_clone_file($cloneFile, $sourceFile, $server_no = 0, $mode = FTP_BINARY)
    {
        if (CGlobal::$storage_server[$server_no]['server_type'] == 'curl') // Upload via cUrl
        {
            $curl_handle = curl_init("http://" . CGlobal::$storage_server[$server_no]['host'] . "/cp?source_file=$sourceFile&source_secret_key=".CGlobal::$storage_server[$server_no]['secret_key']."&dest_file=$cloneFile&dest_secret_key=".CGlobal::$storage_server[$server_no]['secret_key']."&overwrite=1");

			curl_setopt($curl_handle, CURLOPT_HEADER, 0);
            curl_setopt($curl_handle, CURLOPT_VERBOSE, 0);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");

            //execute the API Call
            $returned_data = curl_exec($curl_handle);

            curl_close($curl_handle);
            
            //return $returned_data;
            return (($returned_data == 'OK')?true:false);
        }
        elseif (self::storage_connect($server_no))// Upload via FTP
        {
        	$tmp_foder 	= md5(TIME_NOW . $cloneFile);
        	$tmp_file 	= DIR_CACHE . "img_tmp/$tmp_foder/" . basename($cloneFile);
        	
        	if(ECLib::CheckDir(DIR_CACHE . "img_tmp/$tmp_foder") && ftp_get(CGlobal::$ftp_img_conid[$server_no], $tmp_file, $sourceFile ,$mode))
	        {
	        	if(file_exists($tmp_file) && self::storage_check_dir(dirname($cloneFile),true,$server_no))
	        	{
	                if(ftp_put(CGlobal::$ftp_img_conid[$server_no], $cloneFile ,$tmp_file , $mode))
	                {
	                	@ftp_chmod(CGlobal::$ftp_img_conid[$server_no], 0777, $cloneFile);
	                	
	                	//Xóa thư mục & file tạm
	               		ECLib::remove_dir(DIR_CACHE . "img_tmp/$tmp_foder/");
	                	
	               		//@unlink($tmp_file) ;   
	           			return true;                     
	                }
                }
	        }
        }
        
        return false;
    }
    
    /**
    * Hàm đổi tên file trong Storage
    * @package Storage Upload
    * @param $filePath: tên đầy đủ của file bao gồm cả đường dẫn gốc
    * @param $newName: tên mới của file không bao gồm đường dẫn
    **/
    static function storage_rename_file($filePath,$newName, $server_no = 0)
    {
        if (CGlobal::$storage_server[$server_no]['server_type'] == 'curl') // Upload via cUrl
        {
            $curl_handle = curl_init("http://" . CGlobal::$storage_server[$server_no]['host'] . "/rename?secret_key=".CGlobal::$storage_server[$server_no]['secret_key']."&from=$filePath&to=" . dirname($filePath) . "/$newName");

			curl_setopt($curl_handle, CURLOPT_HEADER, 0);
            curl_setopt($curl_handle, CURLOPT_VERBOSE, 0);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");

            //execute the API Call
            $returned_data = curl_exec($curl_handle);

            curl_close($curl_handle);
            //return $returned_data;
            return (($returned_data == 'OK')?true:false);
        }
        elseif (self::storage_connect($server_no))// Upload via FTP
        {
        	return ftp_rename(CGlobal::$ftp_img_conid[$server_no],"$filePath", dirname($filePath) . "/$newName");      
        }
        
        return false;
    }

    static function storage_delete_file($sourceFileName, $server_no = 0)
    {
        if (CGlobal::$storage_server[$server_no]['server_type'] == 'curl') // delete via cUrl
        {
            //$post_fields['filename'] = $sourceFileName;
            //$post_fields['secret_key'] = CGlobal::$storage_server[$server_no]['secret_key'];
            //$curl_handle = curl_init(CGlobal::$img_server[$server_no].'delete');

            $curl_handle = curl_init(CGlobal::$storage_server[$server_no]['del_link'].'/delete?filename='.$sourceFileName.'&secret_key='.CGlobal::$storage_server[$server_no]['secret_key']);
			//return (' -F filename='.$post_fields['filename'].' -F secret_key='.$post_fields['secret_key']. ' '.CGlobal::$img_server[$server_no].'delete');

			curl_setopt($curl_handle, CURLOPT_HEADER, 0);
            curl_setopt($curl_handle, CURLOPT_VERBOSE, 0);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl_handle, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");

            //execute the API Call
            $returned_data = curl_exec($curl_handle);

            /*if (curl_errno($curl_handle)) {
                // this would be your first hint that something went wrong
                //die('Couldn\'t send request: ' . curl_error($curl_handle));
                return 'Couldn\'t send request: ' . curl_error($curl_handle);
            } else {
                // check the HTTP status code of the request
                $resultStatus = curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
                if ($resultStatus == 200) {
                    // everything went better than expected
                } else {
                    // the request did not complete as expected. common errors are 4xx
                    // (not found, bad request, etc.) and 5xx (usually concerning
                    // errors/exceptions in the remote script execution)
                    //die('Request failed: HTTP status code: ' . $resultStatus);
                    return 'Request failed: HTTP status code: ' . $resultStatus;
                }
            }
            if ($returned_data == 'OK') {
                // everything went better than expected
            } else {
                //die('Request failed: Error: ' . $returned_data);
                return 'Request failed: Error: ' . $returned_data;
            }*/

            curl_close($curl_handle);
            //return $returned_data;
            return (($returned_data == 'OK')?true:false);
        }
        elseif (self::storage_connect($server_no))
        {
            if (@ftp_delete(CGlobal::$ftp_img_conid[$server_no], $sourceFileName))
            {
                return true;
            }
        }
        
        return false;
    }

    static function storage_check_dir($remote_dir_path, $mkdir=true, $server_no = 0)
    {
        $ret = true;

        if (CGlobal::$storage_server[$server_no]['server_type'] == 'curl') return $ret; // Nếu upload bằng cUrl và không phải là upload quảng cáo CPC thì không cần check ftp directory

        if (self::storage_connect($server_no))
        {
            if ($remote_dir_path == '')
                return true;

            $dir 				= explode("/", $remote_dir_path);
            $remote_dir_path 	= "";

            for ($i = 0; $i < count($dir); $i++)
            {
                if ($dir[$i] != '')
                {
                    $remote_dir_path.="/" . $dir[$i];
                    
                    if (!@ftp_chdir(CGlobal::$ftp_img_conid[$server_no], $remote_dir_path))
                    {
                        if ($mkdir)
                        {
                            @ftp_chdir(CGlobal::$ftp_img_conid[$server_no], "/");

                            if (!@ftp_mkdir(CGlobal::$ftp_img_conid[$server_no], $remote_dir_path))
                            {
                                $ret = false;
                            
                                    break;
                            }
                        }
                        else
                        {
                            $ret = false;
                            break;
                        }
                    }
                }
            }
            
            @ftp_chdir(CGlobal::$ftp_img_conid[$server_no], "/");
        } 
        else
        {
            $ret = false;
            //break;
        }
        
        return $ret;
    }

    //Hàm chia thư mục ảnh!
    static function folderUpload($userid = 0, $folder = '') {//$folder: item, avatar, shop_banner, _common, category
        if (!$userid)
            $userid = User::id();

        if ($folder == '')
        {
        	$folder = '/';
        }
		else
		{
			$folder = "$folder/";
		}
		
        return UP_FOLDER . "/". date('Y/m/d', TIME_NOW) . $folder . round($userid / 1000) . "/$userid/";
        
        //return  date('Y/m/d/',TIME_NOW).$folder.'/'.round($userid/1000).'/'.round($item_id/1000).'/';
    }

    static function getExtension($file) {
        $pos = strrpos($file, '.');
        if (!$pos) {
            return false;
        }
        $str = substr($file, $pos, strlen($file));
        
        return strtolower($str);
    }
}

//register_shutdown_function(array("Upload","storage_close"));
?>